// WebSocketService.ts
import { ref } from 'vue';

interface SubTask {
  id: string;
  name: string;
  status: string;
  result: string;
}

interface WSMessage {
  type: 'new' | 'update' | 'history';
  subtask_list?: Record<string, string>;
  task_id?: string;
  task?: string;
  task_status?: string;
  task_result?: string;
  task_list?: Array<{
    task_id: string;
    task: string;
    task_status: string;
    task_result: string;
  }>;
}

const tasks = ref<SubTask[]>([]);
const isLoading = ref(false);
let socket: WebSocket | null = null;

// 获取配置信息
let apiBaseUrl = '';
let wsBaseUrl = '';

// 加载配置文件
const loadConfig = async () => {
  try {
    const response = await fetch('/config.json');
    const config = await response.json();
    apiBaseUrl = config.apiBaseUrl;
    wsBaseUrl = config.wsBaseUrl;
    console.log('配置加载成功:', config);
  } catch (error) {
    console.error('加载配置文件失败:', error);
    // 使用默认值
    apiBaseUrl = 'http://localhost:8000';
    wsBaseUrl = 'ws://localhost:8000/ws';
  }
};

// 初始化WebSocket连接
const initWebSocket = async () => {
  // 确保配置已加载
  if (!wsBaseUrl) {
    await loadConfig();
  }
  
  socket = new WebSocket(wsBaseUrl);
  
  socket.onopen = () => {
    console.log('WebSocket连接已建立');
  };
  
  socket.onmessage = (event) => {
    const data: WSMessage = JSON.parse(event.data);
    handleWebSocketMessage(data);
  };
  
  socket.onerror = (error) => {
    console.error('WebSocket错误:', error);
  };
  
  socket.onclose = () => {
    console.log('WebSocket连接已关闭');
    // 可以在这里添加重连逻辑
    setTimeout(() => {
      initWebSocket();
    }, 5000);
  };
};

// 处理WebSocket消息
const handleWebSocketMessage = (data: WSMessage) => {
  if (data.type === 'new' && data.subtask_list) {
    // 处理新任务列表
    const newTasks: SubTask[] = [];
    for (const [id, name] of Object.entries(data.subtask_list)) {
      newTasks.push({
        id,
        name,
        status: 'pending',
        result: '等待执行'
      });
    }
    tasks.value = newTasks;
    isLoading.value = false;
  } else if (data.type === 'update' && data.task_id) {
    // 更新特定任务的状态
    const taskIndex = tasks.value.findIndex(task => task.id === data.task_id);
    if (taskIndex !== -1) {
      if (data.task) tasks.value[taskIndex].name = data.task;
      if (data.task_status) tasks.value[taskIndex].status = data.task_status;
      if (data.task_result) tasks.value[taskIndex].result = data.task_result;
    }
  }
};

// 创建新任务
const createNewTask = async (taskDescription: string) => {
  try {
    isLoading.value = true;
    // 确保配置已加载
    if (!apiBaseUrl) {
      await loadConfig();
    }
    const response = await fetch(`${apiBaseUrl}/task/new`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ task: taskDescription })
    });
    
    const data = await response.json();
    return data.task_id;
  } catch (error) {
    console.error('创建任务失败:', error);
    isLoading.value = false;
    throw error;
  }
};

// 开始执行任务
const startTasks = async () => {
  try {
    const subtaskList: Record<string, string> = {};
    tasks.value.forEach(task => {
      subtaskList[task.id] = task.name;
    });
    
    // 确保配置已加载
    if (!apiBaseUrl) {
      await loadConfig();
    }
    
    await fetch(`${apiBaseUrl}/task/start`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: 'ready',
        subtask_list: subtaskList
      })
    });
  } catch (error) {
    console.error('开始任务失败:', error);
    throw error;
  }
};

// 获取历史任务
const fetchHistoryTasks = async () => {
  try {
    // 确保配置已加载
    if (!apiBaseUrl) {
      await loadConfig();
    }
    
    const response = await fetch(`${apiBaseUrl}/task/history`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ type: 'history' })
    });
    
    const data = await response.json();
    return data.task_list || [];
  } catch (error) {
    console.error('获取历史任务失败:', error);
    throw error;
  }
};

// 关闭WebSocket连接
const closeWebSocket = () => {
  if (socket) {
    socket.close();
    socket = null;
  }
};

export {
  tasks,
  isLoading,
  initWebSocket,
  createNewTask,
  startTasks,
  fetchHistoryTasks,
  closeWebSocket
};